<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true"  label-width="100px">
      <el-form-item label="资产名称" prop="collectiveName">
        <el-input
          v-model="queryParams.collectiveName"
          placeholder="请输入资产名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产分类" prop="collectiveSort">
        <treeselect v-model="queryParams.collectiveSort" :options="categoryOptions" :normalizer="normalizer" placeholder="请选择资产分类" style="width:240px" />
      </el-form-item>
      <el-form-item label="采购方式" prop="collectiveType">
          <el-select v-model="queryParams.collectiveType" clearable placeholder="请选择采购方式">
            <el-option
              v-for="dict in dict.type.collective_type"
              :key="dict.value"
              :label="dict.label"
              :value="(dict.value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
      <el-form-item label="报名结束时间" prop="collectiveEndtime">
          <el-date-picker
            v-model="queryParams.collectiveEndtime"
            type="datetime"
            placeholder="选择报名结束日期"
          >
          </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="reportList"
    >
      <el-table-column type="index" label="序号"  align="center" />
      <el-table-column label="资产名称" align="center" prop="collectiveName" />
      <el-table-column label="资产分类" align="center" prop="collectiveSortName" />
      <el-table-column label="采购方式" align="center" prop="collectiveType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.collective_type" :value="scope.row.collectiveType"/>
        </template>
      </el-table-column>
      <el-table-column label="报名结束时间" align="center" prop="collectiveEndtime" />
      <el-table-column label="规格" align="center" prop="collectiveSpecification" />
      <el-table-column label="单价" align="center" prop="collectivePrice" />
      <el-table-column label="集采描述" align="center" prop="collectiveDescription">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            :disabled="scope.row.status==2"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            v-show="scope.row.status==0"
            :disabled="scope.row.status==2"
            type="text"
            @click="handleSubm(scope.row)"
            >提交审批</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            type="text"
            v-if="scope.row.status==1"
            @click="revocationHandle(scope.row)"
            >撤回</el-button
          >
           <el-button
            type="text"
            @click="viewSignIn(scope.row)"
            >查看报名</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工作汇报对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      :width="widths"
      append-to-body
    >
      <el-table v-if="title=='查看报名详情'" :data="signPeopleList"  style="width: 100%">
        <el-table-column prop="nickName" label="姓名" align="center">
        </el-table-column>
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
          </template>
      </el-table-column>
        <el-table-column prop="phonenumber" label="手机号" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="报名时间" align="center">
        </el-table-column>
        <el-table-column prop="status" label="报名状态" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sign_status" :value="scope.row.status"/>
        </template>
        </el-table-column>
        <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleExamine(scope.row,1)"
            >审批通过</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleExamine(scope.row,2)"
            >审批不通过</el-button
          >
          </template>
      </el-table-column>
      </el-table>
      <div v-else>
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="资产名称" prop="collectiveName">
          <el-input
            v-model="form.collectiveName"
            placeholder="请输入资产名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="资产分类" prop="collectiveSort">
          <treeselect v-model="form.collectiveSort" :options="categoryOptions" :normalizer="normalizer"  placeholder="请选择资产分类" />
        </el-form-item>
        <el-form-item label="采购方式" prop="collectiveType" >
          <el-select v-model="form.collectiveType" clearable placeholder="请选择采购方式" style="width:100%">
            <el-option
              v-for="dict in dict.type.collective_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报名结束时间" prop="collectiveEndtime">
          <el-date-picker
            style="width: 100%"
            v-model="form.collectiveEndtime"
            type="datetime"
            placeholder="选择报名结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="规格" prop="collectiveSpecification">
          <el-input v-model="form.collectiveSpecification" placeholder="请填写规格"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="collectivePrice">
          <el-input v-model="form.collectivePrice" placeholder="请填写单价"></el-input>
        </el-form-item>
        <el-form-item label="集采描述" prop="collectiveDescription">
          <el-input
            type="textarea"
            v-model="form.collectiveDescription"
            placeholder="请填写集采描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectClazz } from "@/api/base/clazz";
import { listCategory } from "@/api/oa/category";
import VueQr from 'vue-qr'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { addCollective,editCollective,getCollective,deleteCollective,viewSignPeople,signUpdate } from '@/api/base/buygarden'
import {
  addstuVision,
  delstuVision,
  stuVision,
  updatestuVision,
} from "@/api/base/ill";
import {
  addStudent,
  delStudent,
  listStudent,
  updateStudent,
} from "@/api/base/student";

export default {
  components: {
    Treeselect,VueQr
  },
  name: "buygarden",
  dicts: ["vision_result", "year_type",'collective_type','sys_user_sex','sign_status'],
  data() {
    const leftEye = (rule, value, callback) => {
      if (value > 2) {
        callback(new Error("左眼度数最高为2.0"));
      } else {
        callback();
      }
    };
    const rightEye = (rule, value, callback) => {
      if (value > 2) {
        callback(new Error("右度数最高为2.0"));
      } else {
        callback();
      }
    };
    return {
      title: "",
      open: false,
      form: {},
      rules: {
        collectiveName:[
          { required: true, message: "资产名称不能为空", trigger: "blur" }
        ],
        collectiveSort:[
          { required: true, message: "资产分类不能为空", trigger: "blur" }
        ],
      },
      // 总条数
      total: 0,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // schoolCode: this.$store.getters.schoolCode,
      },
      // 资产分类表格数据
      categoryOptions: [],
      classList: [],
      reportList: [],
      stuList: [],
      widths:'500px',
      signPeopleList:[],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  created() {
    /**列表接口**/
    this.getList();
    listCategory().then(response => {
      this.categoryOptions = [];
      const data = { id: 0, title: '顶级节点', children: [] };
      data.children = this.handleTree(response.data, "id", "pid");
      this.categoryOptions.push(data);
    });
  },
  methods: {
    // 查看报名
    async viewSignIn(row){
      this.open = true;
      this.widths = '900px'
      this.title = "查看报名详情";
      const res = await viewSignPeople({collectiveId:row.collectiveId || row.id})
      // console.log('res====',res);
      if(res.code === 200){
        this.signPeopleList = res.data
      }

    },
    // 撤回
    async revocationHandle(row){
      row.status = '2'
      const res= await editCollective(row)
      if(res.code === 200){
        this.$message.success('撤回成功')
        this.getList()
      }
    },
    // 报名审批
    async handleExamine(row,status){
      row.status = status
      const res= await signUpdate(row)
      if(res.code === 200){
        this.$message.success('审批成功')
        this.viewSignIn(row)
      }
    },
    // 提交审批
    async handleSubm(row) {
      row.status = '1'
      const res= await editCollective(row)
      if(res.code === 200){
        this.$message.success('审批成功')
        this.getList()
      }

    },
    /** 转换资产分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.title,
        children: node.children
      };
    },
    /** 查询视力列表 */
    async getList() {
      try {
        this.loading = true;
        const data = await getCollective(this.queryParams);
        this.total = data.total;
        this.reportList = data.rows
        this.loading = false;
      } catch (e) {
        console.log(e);
      }
    },
    /** 查询条件班级列表 */
    async getFormclassList() {
      try {
        let params = {};
        this.$set(this.queryParams, "classId", "");
        if (this.queryParams.grade) params.year = this.queryParams.grade;
        const { rows } = await selectClazz(params);
        this.classList = rows.map((item) => {
          return {
            id: item.id,
            label: item.title,
          };
        });
      } catch (e) {
        console.log(e);
      }
    },
    /** 查询班级列表 */
    async getclassList() {
      try {
        let params = {};
        this.$set(this.form, "classId", "");
        this.$set(this.form, "stuId", "");
        if (this.form.grade) params.year = this.form.grade;
        const { rows } = await selectClazz(params);
        this.classList = rows.map((item) => {
          return {
            id: item.id,
            label: item.title,
          };
        });
      } catch (e) {
        console.log(e);
      }
    },
    /**查询学生**/
    async getStuList() {
      try {
        let params = {};
        this.$set(this.form, "stuId", "");
        if (this.form.classId) params.classId = this.form.classId;
        const data = await listStudent(params);
        this.stuList = data.rows;
      } catch (e) {
        console.log(e);
      }
    },
    /**提交*/
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            editCollective(this.form).then(response => {
              if(response.code==200){
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }else{
                this.msgError(response.msg);
              }

            });
          } else {
            addCollective(this.form).then(response => {
              if(response.code==200){
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }else{
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.form = JSON.parse(JSON.stringify(row));
      /**班级**/
      this.getclassList();
      /**学生接口**/
      this.getStuList();
      this.open = true;
      this.title = "修改学生视力信息";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.widths = '500px'
      this.title = "添加园内集采";
    },
    // 编辑
    handleEdit(row){
      this.open = true;
      this.widths = '500px'
      this.title = "编辑园内集采";
      this.form = row
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      // this.$confirm('是否确认删除学生编号为"' + ids + '"的数据项?', "警告", {
      this.$confirm("是否确认删除选中的数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return deleteCollective(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuId: null,
        leftEyeVision: null,
        rightEyeVision: null,
        visionResult: null,
        classId: null,
        // schoolCode: this.$store.getters.schoolCode,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>
